package com.java1234.controller;

import com.java1234.entity.SysUser;
import com.java1234.service.SysUserService;
import com.java1234.util.DecryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户注册Controller
 */
@RestController
@RequestMapping("/api/auth")
@Validated
public class RegisterController {

    private final SysUserService userService;
    private final DecryptUtil decryptUtil; // 解密工具

    @Autowired
    public RegisterController(SysUserService userService, DecryptUtil decryptUtil) {
        this.userService = userService;
        this.decryptUtil = decryptUtil;
    }

    /**
     * 用户注册接口
     *
     * @param user 注册用户信息
     * @return 注册结果信息
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, String>> register(@RequestBody @Valid SysUser user) {
        try {
            // 假设前端传递的是加密后的密码
            String encryptedPassword = user.getPassword();

            // 解密新密码
            String decryptedPassword = decryptUtil.decrypt(encryptedPassword);
            user.setPassword(decryptedPassword); // 更新用户的密码为解密后的密码

            userService.registerUser(user);
            // 使用 Collections.singletonMap 创建返回值
            return ResponseEntity.status(HttpStatus.CREATED).body(Collections.singletonMap("message", "User registered successfully"));
        } catch (Exception e) {
            // 使用自定义异常或者直接返回错误信息
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            // 如果抛出的是运行时异常，比如用户名已存在，返回400状态码
            if (e instanceof RuntimeException && "用户名已存在".equals(e.getMessage())) {
                return ResponseEntity.badRequest().body(errorResponse);
            }
            // 对于其他异常，返回500状态码
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}